/**
 * Copyright (c) 2008,中企动力华南研发中心
 * All rights reserved.
 */

package com.ce.pms.common.web;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.ce.pms.base.web.PmsBaseAction;
import com.ce.pms.common.util.PmsUtilityComparator;
import com.ce.pms.common.util.UpLoadFile;
import com.ce.pms.common.vo.ChooseHouseVO;
import com.ce.pms.house.service.IBuildingService;
import com.ce.pms.house.service.IHouseService;
import com.ce.pms.house.service.IImageService;
import com.ce.pms.house.service.IManageAreaService;
import com.ce.pms.house.vo.BuildingVO;
import com.ce.pms.house.vo.FlatVO;
import com.ce.pms.house.vo.HouseGrpVO;
import com.ce.pms.house.vo.HouseSearchVO;
import com.ce.pms.house.vo.ImageVO;
import com.ce.util.BlankUtil;
import com.sitechasia.webx.core.annotation.Out;
import com.sitechasia.webx.core.annotation.Read;
/**
 * 逻辑、功能相关描述:
 * @author 易贤建  编写日期：2008-7-4
 */

public class CommonAction extends PmsBaseAction {
	private IBuildingService buildingService = null;
	private IHouseService houseService = null;
	private IManageAreaService manageAreaService=null;
	private IImageService imageService = null;

	/**
	 * Function:初始化选择楼栋,如果有buildingIDs,将过滤这些楼栋
	 * @param parentFrameId 调用窗口的iFrame id
	 * @param precinctId 管理区ID
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-7-10
	 * Edit author:罗军林
	 * Edit on:
	 * Why:
	 */
	public String initCommonSelectBuilding(	@Read(key="precinctId") Long precinctId,
											@Read(key="parentFrameId") String parentFrameId)
	{
		List<BuildingVO> noUseBuildingList=manageAreaService.getBuildingIdsNotUse();
		List<BuildingVO> isUsedBuildingListByPrecinct=new ArrayList<BuildingVO>();
		if(null != precinctId){
			isUsedBuildingListByPrecinct=manageAreaService.getBuildingsBy(precinctId);
		}
		List empty = addEmptyLine(noUseBuildingList);


		//当前管理区被引用的以及所以其它没有被引用的楼栋集合
		noUseBuildingList.addAll(isUsedBuildingListByPrecinct);

		setAttribute("parentFrameId", parentFrameId);
		setAttribute("isUsedBuildingListByPrecinct", isUsedBuildingListByPrecinct);
		setAttribute("noUseBuildingList", noUseBuildingList);
		setAttribute("emptyList", empty);

		return "selectBuilding";
	}


	   /**
	   * Function:图片预览
	   * @param
	   * @return
	   * Create author:yixianjian
	   * Create on:2008-6-26
	   * Edit author:
	   * Edit on:
	   * Why:
	    */
	public String initImagePreview(@Read(key="filePath") String filePath){
		try {
			filePath=(String)java.net.URLDecoder.decode(filePath,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		  boolean isLocalView = false;
		  if(filePath.indexOf(".") != -1)
		  {
			  isLocalView = true;
		  }
		  setAttribute("filePath", filePath);
		  setAttribute("isLocalView", isLocalView);
		  return "imagePreview";
	   }

	   public void getJpg(@Read (key="fileId") Long fileId)
	   		throws Exception
	   {
		  ImageVO image =  imageService.findImageByID(fileId);
		  byte data[]=UpLoadFile.getFileInputStream(image);
        getResponse().setHeader("Content-Disposition","attachment; filename=df");
        java.io.OutputStream out1 = getResponse().getOutputStream();
        out1.write(data);
        out1.flush();
        out1.close();
	   }

	   /**
	   * Function:初始化选择多个房间列表页面主页面
	   * @param parentFrame 指定父页面ID
	   * @return
	   * Create author:yixianjian
	   * Create on:2008-7-4
	   * Edit author:
	   * Edit on:
	   * Why:
	    */
	   public String chooseMultiHouse(@Read(key="parentFrame")@Out(key="parentFrame") String parentFrame){
		   List<BuildingVO> buildVO = buildingService.getAllBuildingList();
		   List<ChooseHouseVO> chooseHouseList = createSelectNode(buildVO);
		   setAttribute("buildingList", chooseHouseList);
		   return "chooseMultiHouse";
	   }
	   /**
	   * Function:初始化选择多个房间列表页面列表页面
	   * @param
	   * @return
	   * Create author:yixianjian
	   * Create on:2008-7-4
	   * Edit author:
	   * Edit on:
	   * Why:
	    */
	   public String chooseMultiHouseList(@Read ChooseHouseVO chooseHouseVO){
		   HouseSearchVO houseSearchVO = getHouseSearchVO(chooseHouseVO);
		   if(houseSearchVO == null)
			   return "chooseMultiHouseList";

		   List<FlatVO> flatVO = houseService.queryHouseListBy(houseSearchVO);

		   List<List> flatList = processFlatList(flatVO);
		   setAttribute("members", flatList);

		   Integer storey = getStoreyHouseCountList(flatList); //获取该楼栋的层数
		   if(storey == null) storey = new Integer(0);
		   setAttribute("storey",storey);

		   Integer maxHouseCount = getMaxStoreyHouseCount(flatList); //获取房号最多的楼层数
		   setAttribute("maxHouseCount", maxHouseCount);

		   return "chooseMultiHouseList";
	   }

		/**
		 *
		* Function:获取该楼栋的层数。
		* @param 房屋列表
		* @return
		* Create author:yixianjian
		* Create on:2008-5-22
		* Edit author:
		* Edit on:
		* Why:
		 */
		public Integer getStoreyHouseCountList(List<List> memberList){
			if(memberList == null || memberList.isEmpty())
				return null;
			if(memberList.get(0) == null)
				return null;
			return  Integer.valueOf(memberList.get(0).get(0).toString());
		}

		/**
		 *
		* Function:获取楼栋层最大的房屋数.
		* @param房屋列表
		* @return
		* Create author:yixianjian
		* Create on:2008-5-22
		* Edit author:
		* Edit on:
		* Why:
		 */
		public Integer getMaxStoreyHouseCount(List<List> memberList){
			int maxCount = 0;
			if(memberList == null || memberList.isEmpty()) return maxCount;
			for(List houseItems : memberList)
				maxCount = maxCount > houseItems.size() ? maxCount : houseItems.size();
			return Integer.valueOf(maxCount);
		}
		/**
		 * 功能描述:  根据提供的chooseHouseVO组装houseSearchVO<br>
		 * @param chooseHouseVO
		 * @return
		 * Create author:yixianjian <br>
		 * Create on:2008-7-14  <br>
		 * Edit author:  <br>
		 * Edit on:    <br>
		 * Why:     <br>
		 */
		private HouseSearchVO getHouseSearchVO(ChooseHouseVO chooseHouseVO){
			if(BlankUtil.isBlank(chooseHouseVO.getBuildId()))
				return null;
			HouseSearchVO houseSearchVO = new HouseSearchVO();
			houseSearchVO.setBuildingId(chooseHouseVO.getBuildId());
			houseSearchVO.setHouseGrpid(chooseHouseVO.getHouseGrpId());
			return houseSearchVO;
		}

		/**
		 *
		* Function:遍历每个flatDO,将flatDO按照每个楼层一个list方式排列。
		* @param
		* @return
		* Create author:yixianjian
		* Create on:2008-6-6
		* Edit author:
		* Edit on:
		* Why:
		 */
		private List processFlatList(List<FlatVO> flatList){
			if(flatList == null || flatList.size() == 0)
				return null;
			List<List> list = new ArrayList<List>();
			List sameFloorFlatList = null;

			Iterator<FlatVO> iterator = flatList.iterator();
			int index;
			while(iterator.hasNext()){
				FlatVO flatVO = iterator.next();
				index = isFloorExists(list,flatVO);
//				当前楼层同层的 List已经存在了，只需找到，然后添加了
				if(index != -1){
					list.get(index).add(flatVO);
				}else{
					//但前楼层list不存在，创建一个新的list，然后添加
					sameFloorFlatList = new ArrayList();
					sameFloorFlatList.add(flatVO.getFloor());
					sameFloorFlatList.add(flatVO);
					list.add(sameFloorFlatList);
				}
			}
			return list;
		}

		private int isFloorExists(List<List> list,FlatVO flatItem){
			if(list.isEmpty())
				return -1;
			List inside = list.get(list.size() - 1 );
			if(flatItem.getFloor().equals(inside.get(0))){
				return list.size() -1;
			}
			return -1;
		}

		/**
		* Function:将查询到的楼栋列表转换为页面下拉列表用的VO
		* Create author:yixianjian
		* Create on:2008-6-6
		* Edit author:
		* Edit on:
		* Why:
		 */
		private List<ChooseHouseVO> createSelectNode(List<BuildingVO> buildList){
			HouseGrpVO houseGrp = null;
			String id = null;
			String text = null;
			List<ChooseHouseVO> chooseHouseVOList = new ArrayList<ChooseHouseVO>();
			ChooseHouseVO temp = null;
			for(BuildingVO builditem : buildList){

				Set<HouseGrpVO> groups = builditem.getHouseGrpVos();
				Iterator<HouseGrpVO> iterator = groups.iterator();
				//不存在管理单元，先赋值再说。存在，在下面再重新设值

				if("1".equalsIgnoreCase(builditem.getHasCell())){
					while(iterator.hasNext()){
						houseGrp = iterator.next();
						temp = new ChooseHouseVO();
						id = builditem.getKeyword() + "," + houseGrp.getKeyword();
						text = builditem.getName() +"-" + houseGrp.getName() + "单元";
						temp.setBuildSeqNo(builditem.getSeqNo());
						temp.setSelectId(id);
						temp.setSelectText(text);
						chooseHouseVOList.add(temp);
					}
				}else{
					temp = new ChooseHouseVO(builditem.getSeqNo(),builditem.getKeyword().toString(),builditem.getName());
					chooseHouseVOList.add(temp);
				}

			}
			Collections.sort(chooseHouseVOList, PmsUtilityComparator.getComparator());
			return chooseHouseVOList;
		}

		/**
		 * Function:对异常的页面进行转发
		 * @param
		 * @return
		 * Create author:xuhaidui
		 * Create on:2008-7-10
		 * Edit author:
		 * Edit on:
		 * Why:
		 */
		public String forwardException(@Read(key="exceptionType")String exceptionType,
				@Read(key="message")String message){

			if(!BlankUtil.isBlank(message)){
               this.getRequest().setAttribute("messageSession", getLocaleMessage(message));
			}
		   return exceptionType;
		}

		/** 功能描述:增加空行<br>
		 * @param notUseBuildingList
		 * @return<br>
		 * Create author:罗军林<br>
		 * Create on:2008-7-22<br>
		 * Edit author:<br>
		 * Edit on:<br>
		 * Why:<br>
		 */
		private List addEmptyLine(List<BuildingVO> notUseBuildingList) {
			List empty = new ArrayList();
			if(notUseBuildingList.size()<26){
				for(int i=notUseBuildingList.size()+1;i<26;i++){
					empty.add(i);
				}
			} else {
				for(int i=notUseBuildingList.size()%5+1;i<6;i++){
					empty.add(i);
				}
			}
			return empty;
		}

		public void setBuildingService(IBuildingService buildingService) {
			this.buildingService = buildingService;
		}

		public void setHouseService(IHouseService houseService) {
			this.houseService = houseService;
		}


		/**
		 * @return the manageAreaService
		 */
		public IManageAreaService getManageAreaService() {
			return manageAreaService;
		}


		/**
		 * @param manageAreaService the manageAreaService to set
		 */
		public void setManageAreaService(IManageAreaService manageAreaService) {
			this.manageAreaService = manageAreaService;
		}


		public void setImageService(IImageService imageService) {
			this.imageService = imageService;
		}


}
